package com.shenbianyun.cloudcaring.payment;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class HttpInvoker {

    public void sendGet(String relativeUrl, Map<String, String> param) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                .build();


        param.put("app_id", "1830891706061811713");
        String sign = MD5SignUtils.getSign("bSsXY9fA3IM31YuptH7BJMp9njNR1g6s", param);
        param.put("sign", sign);

        StringBuilder queryString = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            queryString.append(String.format("&%s=%s", next.getKey(), next.getValue()));
        }
        relativeUrl = relativeUrl + "?" + queryString.substring(1);
        // 创建POST请求
        Request request = new Request.Builder()
                .url("huibutie.host:https://testgateway.serviceshare.com/cloud-caring/openapi" + relativeUrl)
                .get()
                .build();

        // 发送请求并处理响应
        getResponseResult(client, request);
    }


    /**
     * 单独指定 host 的请求
     */
    public static String sendPost(String host, String relativeUrl, Map param) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                .build();
        // 创建请求体
        MediaType mediaType = MediaType.parse("application/json");

        String requestBody = JSONObject.toJSONString(param);
        RequestBody body = RequestBody.create(mediaType, requestBody);
        // 创建POST请求
        Request request = new Request.Builder()
                .url(host + relativeUrl)
                .post(body)
                .build();
        String response = getResponseResult(client, request);
        return response;
    }

    /**
     * 发送请求并处理响应
     *
     * @param client
     * @param request
     * @return
     */
    private static String  getResponseResult(OkHttpClient client, Request request) {
        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string(); // 仅读取一次
            return response.isSuccessful() ? responseBody : "请求失败: " + responseBody;
        } catch (IOException e) {
            return "请求异常: " + e.getMessage();
        }

    }
}
